package com.ytjj.quartz.task;

import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.dto.mqdto.SmsDto;
import com.ytjj.common.utils.feishu.FeiShuUtil;
import com.ytjj.qmyx.mall.model.MsgFailLog;
import com.ytjj.quartz.dao.MsgFailLogDao;
import com.ytjj.quartz.model.SmsFailStaticsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author jiawei
 * @date 2023年04月23日 15:07
 * @describe
 */
@Component
@Slf4j
public class MessageTask{
	@Resource
	private MsgFailLogDao msgFailLogDao;
	@Resource
	private RabbitTemplate rabbitTemplate;

	ThreadPoolExecutor pools = new ThreadPoolExecutor(10, 20, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024 * 1024));

	/**
	 * 短信发送失败定时统计每天10点
	 */
	@Scheduled(cron = "0 0 10 * * ?")
	public void sMsFailStaticsTask() {
		log.debug("===== 开始统计短信发送失败 =====");
		StringBuffer text = new StringBuffer("短信发送失败每日统计\n");
		try {
			Calendar rightNow = Calendar.getInstance();
			Integer day = rightNow.get(Calendar.DAY_OF_MONTH);
			//前一个月发送失败
			List<SmsFailStaticsResponse> sendFailMonthData = new ArrayList<>();
			//前一个月提交失败
			List<SmsFailStaticsResponse> submitFailMonthData = new ArrayList<>();
			if(day == 1){
				sendFailMonthData =  msgFailLogDao.getSendFailStaticsByMonth();
				submitFailMonthData = msgFailLogDao.getSubmitFailStaticsByMonth();
			}
			//前一日发送失败
			List<SmsFailStaticsResponse> sendFailDayData = msgFailLogDao.getSendFailStaticsByDay();
			//前一日提交失败
			List<SmsFailStaticsResponse> submitFailDayData = msgFailLogDao.getSubmitFailStaticsByDay();
			if(!CollectionUtils.isEmpty(submitFailMonthData)){
				int sum = submitFailMonthData.stream().mapToInt(a -> a.getTotal()).sum();
				text.append("\t上月提交失败数："+sum+"\n");
				submitFailMonthData.forEach(e->{
					text.append("\t\t"+e.getTotal()+"条\t"+e.getCodeDesc()+"\n");
				});
			}
			if(!CollectionUtils.isEmpty(sendFailMonthData)){
				int sum = sendFailMonthData.stream().mapToInt(a -> a.getTotal()).sum();
				text.append("\t上月发送失败数："+sum+"\n");
				sendFailMonthData.forEach(e->{
					text.append("\t\t"+e.getTotal()+"条\t"+e.getCodeDesc()+"\n");
				});
			}
			if(!CollectionUtils.isEmpty(submitFailMonthData) || !CollectionUtils.isEmpty(sendFailMonthData)){
				text.append("\t----------------------------\n");
			}
			if(!CollectionUtils.isEmpty(submitFailDayData)){
				int sum = submitFailDayData.stream().mapToInt(a -> a.getTotal()).sum();
				text.append("\t昨日提交失败数："+sum+"\n");
				submitFailDayData.forEach(e->{
					text.append("\t\t"+e.getTotal()+"条\t"+e.getCodeDesc()+"\n");
				});
			}
			if(!CollectionUtils.isEmpty(sendFailDayData)){
				int sum = sendFailDayData.stream().mapToInt(a -> a.getTotal()).sum();
				text.append("\t昨日发送失败数："+sum+"\n");
				sendFailDayData.forEach(e->{
					text.append("\t\t"+e.getTotal()+"条\t"+e.getCodeDesc()+"\n");
				});
			}
		} catch (Exception e) {
			text.append("统计出错："+e.getMessage());
		} finally {
			FeiShuUtil.sendMsg(text.toString());
		}
	}

	/**
	 * 诈骗提醒短信通知 条件：发货后2天 （需要的时候再开启）
	 */
//	@Scheduled(cron = "0 0 0/1 * * ?")
	public void sendFraudReminder() {
		String template = "温馨提醒：近期有不法分子以购物信息冒充平台，以微信百万保障到期会收费、快递丢件等形式联系，切勿相信，如已被骗请报警!";
		List<MsgFailLog> deliveredByTime = msgFailLogDao.getDeliveredByTime();
		log.info("=========定时任务【开始】发送温馨提示："+deliveredByTime.size()+"条=====");
		deliveredByTime.forEach(e->{
			pools.execute(() -> {
				String phone = e.getPhone();
				String content = e.getContent();
				Pattern pattern = Pattern.compile("【(.+?)】");
				Matcher matcher = pattern.matcher(content);
				if (matcher.find()) {
					String sign = matcher.group(1);
					//只有XXXX才需要
					if("XXXX优品".equals(sign)){
						SmsDto dto = new SmsDto();
						dto.setType(7);
						dto.setPhone(phone);
						dto.setCode(template);
						dto.setChannel("【"+sign+"】");
						rabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
						MsgFailLog msgFailLog = new MsgFailLog();
						msgFailLog.setId(e.getId());
						msgFailLog.setSendFraudReminderTime(new Date());
						//保存发送时间
						msgFailLogDao.updateMsgFailLogById(msgFailLog);
					}
				}
			});
		});
		log.info("=========定时任务【结束】发送温馨提示："+deliveredByTime.size()+"条=====");
	}
}
